import json
import os
from datetime import datetime
import random
import threading

# 文件路径常量
JSON_FILE = './app/records.json'
# 添加全局状态变量
RECORD_COUNTER = 0  # 当日已生成记录数
CURRENT_DAY = datetime.now().day  # 当前日期


def generate_record():
    """生成单条记录并安排下次生成"""
    global RECORD_COUNTER, CURRENT_DAY
    
    # 检查日期变更
    if datetime.now().day != CURRENT_DAY:
        print("检测到日期变更，重置计数器")
        RECORD_COUNTER = 0
        CURRENT_DAY = datetime.now().day
    
    # 生成记录
    if RECORD_COUNTER < 20:
        record = {
            "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "caller": "admin",
            "status": "success" if RECORD_COUNTER != 13 else "processing",
            "input": f"test{RECORD_COUNTER+1}.jpg",
            "result": f"result{RECORD_COUNTER+1}.png"
        }
        write_records([record])  # 立即写入
        RECORD_COUNTER += 1
        
        # 安排下次生成
        interval = random.randint(1800, 3300)  # 30-55分钟（秒数）
        threading.Timer(interval, generate_record).start()
        print(f"已生成{RECORD_COUNTER}/20条, 下次生成在{interval / 60}小时后")
    else:
        print("今日20条记录已生成完毕")


def start_daily_generation():
    """启动每日记录生成"""
    global RECORD_COUNTER, CURRENT_DAY
    RECORD_COUNTER = 0
    CURRENT_DAY = datetime.now().day
    generate_record()  # 启动首次生成


def read_records():
    """读取JSON文件记录"""
    print(f"正在读取文件路径：{os.path.abspath(JSON_FILE)}")
    print(os.path.exists(JSON_FILE))
    if not os.path.exists(JSON_FILE):
        return []
    with open(JSON_FILE, 'r', encoding='utf-8') as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return []

def write_records(records):
    """写入记录到JSON文件（追加模式）"""
    existing = read_records()
    updated = existing + records
    
    with open(JSON_FILE, 'w', encoding='utf-8') as f:
        json.dump(updated, f, indent=2, ensure_ascii=False)
    
    print(f'成功写入{len(records)}条新记录，当前总记录数：{len(updated)}')


# if __name__ == '__main__':
#     # 生成当日记录
#     new_records = generate_records()

#     # 写入文件
#     write_records(new_records)